#!/bin/bash

#
# This file is distributed under the MIT License. See LICENSE.md for details.
#

SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

INPUT=""
OPTIMIZE=0
SKIP=0
SUPPORT_CONFIG=normal

set -e

while [[ $# > 0 ]]
do
    key="$1"
    case $key in
        -O0)
            OPTIMIZE="0"
            shift
            ;;
        -O1)
            OPTIMIZE="1"
            shift # past argument
            ;;
        -O2)
            OPTIMIZE="2"
            shift # past argument
            ;;
        -trace)
            SUPPORT_CONFIG="trace"
            shift # past argument
            ;;
        -s)
            SKIP="1"
            shift # past argument
            ;;
        --)
            shift
            break
            ;;
        *)
            # unknown option
            if [ -z "$INPUT" ]; then
                INPUT="$key"
            else
                break;
            fi
            shift
            ;;
    esac
done

# Output file names
LL="$INPUT.ll"
LINKED_LL="$INPUT.linked.ll"
REVAMB_LOG="$LL.log"
LL_OPT="$INPUT.opt.ll"
CSV="$LL.li.csv"
OBJ="$LL.o"

# Required programs
export PATH="$SCRIPT_PATH:$PATH"
CC="${CC:-cc}"
LINK="llvm-link"
LLC="llc"
OPT="opt"
REVAMB="revamb"
TOOPT="li-csv-to-ld-options"

# Read endianess and architecture bytes
ARCHID=$(python -c '
from binascii import hexlify
import sys
file = open(sys.argv[1], "rb")
file.seek(5)
result = hexlify(file.read(1))
file.seek(17)
result += hexlify(file.read(2))
file.close()
print(result.decode("utf-8"))' "$INPUT")

case "$ARCHID" in
    010028)
        ARCH=arm;
        ;;
    020200)
        ARCH=mips;
        ;;
    01003e)
        ARCH=x86_64;
        ;;
    *)
        echo "Unknown architecture: $ARCHID"
        exit 1
        ;;
esac

SUPPORT_NAME="support-$ARCH-$SUPPORT_CONFIG.ll"
SUPPORT_PATH="$SCRIPT_PATH/../share/revamb/$SUPPORT_NAME"

if [ '!' -e "$SUPPORT_PATH" ]; then
    SUPPORT_PATH="$SCRIPT_PATH/$SUPPORT_NAME"
    if [ '!' -e "$SUPPORT_PATH" ]; then
        echo "Can't find $SUPPORT_NAME"
        exit 1
    fi
fi

if [ "$SKIP" -eq 0 ]; then
    "$REVAMB" -g ll --debug jtcount,osrjts --use-sections "$INPUT" "$LL" "$@" |& tee "$REVAMB_LOG"
fi

"$LINK" "$LL" "$SUPPORT_PATH" -o "$LINKED_LL" -S

OUTPUT="$INPUT.translated"
if [ "$OPTIMIZE" -eq 0 ]; then
    "$LLC" -O0 -filetype=obj "$LINKED_LL" -o "$OBJ"
elif [ "$OPTIMIZE" -eq 1 ]; then
    "$LLC" -O2 -filetype=obj "$LINKED_LL" -o "$OBJ" -regalloc=fast -disable-machine-licm
elif [ "$OPTIMIZE" -eq 2 ]; then
    "$OPT" -O2 -S "$LINKED_LL" -o "$LL_OPT"
    "$LLC" -O2 -filetype=obj "$LL_OPT" -o "$OBJ" -regalloc=fast -disable-machine-licm
fi

"$CC" $("$TOOPT" "$CSV") \
      "$OBJ" \
      -lz -lm -lrt \
      -o "$OUTPUT" \
      -fno-pie
